import { reactive, onMounted, onBeforeUnmount, getCurrentInstance, defineProps, withDefaults } from 'vue';
import page from './page.ts';
import { useRouter, useRoute } from 'vue-router';
export function useListComponent(props: any = {}) {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;
  const options = reactive({
    //库区
    area: [],
  });
  //页面信息
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    warehouseCode: '', //仓库code
    //分类
    tabs: {
      title: '库区', //分类
      search: '', //搜索
      activeKey: 'areaCode', //唯一值key
      titleKey: 'areaName', //唯一值key
      active: '', //选中值
      list: [], //数据
      //分类操作
      operation: [
        {
          title: '编辑',
          icon: 'Edit',
          click: (row: any, index: number) => {
            proxy.$messageInputBox(`请填写新的库区名称！原库区名称【${row.areaName}】`, (value: string) => {
              proxy.$api.WarehouseArea.UpdateWarehouseArea({
                ...row,
                areaName: value,
              })
                .then((res: any) => {
                  ElMessage({
                    message: `修改成功`,
                    type: 'success',
                  });
                  getTabs();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '删除',
          icon: 'Delete',
          click: (row: any, index: number) => {
            proxy.$messageBox('是否删除当前数据，请确认！', () => {
              proxy.$api.WarehouseArea.DeleteWarehouseArea({
                entityID: row.areaID, //	对象主键ID
              })
                .then((res: any) => {
                  ElMessage({
                    message: `删除成功`,
                    type: 'success',
                  });
                  getTabs();
                  const _tabs = dataInfo.tabs;
                  if (row.areaCode === _tabs.active) {
                    clickTabs(_tabs.list[index - 1]);
                  }
                })
                .catch(() => {});
            });
          },
        },
      ],
      //分类点击列表
      click: (row: any, index: number) => {
        clickTabs(row);
      },
      add: {
        //分类新建按钮
        click: () => {
          proxy.$messageInputBox(`请填写新的库区名称`, (value: string) => {
            proxy.$api.WarehouseArea.AddWarehouseArea({
              areaName: value,
              warehouseCode: dataInfo.warehouseCode,
            })
              .then((res: any) => {
                ElMessage({
                  message: `修改成功`,
                  type: 'success',
                });
                getTabs();
              })
              .catch(() => {});
          });
        },
      },
    },
    table: {
      title: page.title, //表格-标题
      tbodyList: 4,
      //表格-内容数据
      tbody: [],
      rowKey: '',
      theadCode: '', //basedatatable
      //表格-表头数据
      thead: [],
      //表格-搜索数据
      search: {
        pageIndex: 1, //当前页码
        pageSize: 100, //每页显示数据的数量
        totalCount: 0, //总数量
        queryDataBaseFiled: '', // 关键字查询字段，空值查询全部
        likeWords: '', // 查询关键字，空值查询全部
        beginTime: '', // 日期范围-开始时间
        endTime: '', // 日期范围-结束时间
        orderByFiled: '', // 排序字段
        orderByType: 0, // 排序方式，0-倒序,1-升序
        onlySelf: 0, // 是否只查询自己创建的，0：查所有、1：只查自己创建的
        //差异化
        warehouseCode: '', // 仓库编码
        warehouseAreaCode: '', // 库区编码
        areaShelfState: -1, // 状态:-1:全部；0待确认；1已确认；2已作废
        ...props.search,
      },
      //多选
      checkbox: {
        state: true,
        selectable: (row: any) => {
          return props.selectable && typeof props.selectable === 'function' ? props.selectable(row) : true;
        },
        list: [],
      },
      //表格-按钮数据
      btns: [
        {
          title: '导出数据',
          icon: 'Download',
          type: '',
          children: [
            {
              title: '导出当页数据',
              click: () => {
                setLoading('导出当页数据,请稍等');
                exportBtn(dataInfo.table.tbody);
              },
            },
            {
              title: '导出全部数据',
              click: () => {
                setLoading('正在导出全部数据,请稍等');
                proxy.$api.Business.GetMatchPageEmployees({
                  ...dataInfo.table.search,
                  pageIndex: 1,
                  pageSize: 10000,
                })
                  .then((res: any) => {
                    exportBtn(res.list);
                  })
                  .catch(() => {
                    dataInfo.loading = false;
                  });
              },
            },
            {
              title: '导出选中数据',
              click: () => {
                setLoading('导出选中数据,请稍等');
                exportBtn(dataInfo.table.checkbox.list);
              },
            },
          ],
        },
        {
          title: '新建',
          icon: 'Plus',
          type: 'primary',
          click: () => {
            proxy.$openPup(props.pupAdd, 1);
            props.pupAdd.form.areaCode = dataInfo.tabs.active;
          },
        },
      ],
      //列表双击
      // dblclick: (row: any) => {
      // },
      //表格-列表搜索
      operation: [
        {
          title: '编辑',
          icon: 'Edit',
          click: (row: any) => {
            proxy.$openPup(props.pupWarehouseLocation, 2);
            props.pupWarehouseLocation.form = JSON.parse(
              JSON.stringify({
                ...row,
                isFinishedProductInventory: row.isFinishedProductInventory === 1,
              }),
            );
          },
        },
        {
          title: (row: any) => {
            return row.isEnabled === 1 ? '禁用' : '启用';
          },
          icon: 'Edit',
          click: (row: any, index: number) => {
            proxy.$api.WarehouseAreaShelf.IsDisabledWarehouseAreaShelf({
              entityID: row.areaShelfID,
              isDisabled: row.isEnabled === 1, //Type为0时，传0为启用，1为禁用，Type为1时，传1为待确认，2为作废
            })
              .then((res: any) => {
                ElMessage({
                  message: `${row.isEnabled === 1 ? '禁用' : '启用'}成功`,
                  type: 'success',
                });
                getTbody();
              })
              .catch(() => {});
          },
        },
        {
          title: '删除',
          icon: 'Delete',
          click: (row: any, index: number) => {
            proxy.$messageBox('是否删除当前数据，请确认！', () => {
              proxy.$api.WarehouseAreaShelf.DeleteWarehouseAreaShelf({
                entityID: row.areaShelfID,
                entityCode: row.areaShelfCode,
              })
                .then((res: any) => {
                  proxy.$message(`删除成功`);
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
      ],
    },
  });
  // 获取tabs数据
  const getPath = (obj: any, row?: any) => {
    const path = router.resolve(obj);
    // 在新窗口或标签页中打开目标路径
    const newWindow: any = window.open(path.href, '_blank');
    newWindow;
  };
  // 获取tabs数据
  const getTabs = () => {
    proxy.$api.Business.GetMatchWarehouseAreas({
      warehouseCode: dataInfo.warehouseCode,
      warehouseAreaState: '',
      likeWords: '',
    }).then((res: any) => {
      options.area = res.map((el: any) => ({
        ...el,
        label: el.areaName,
        value: el.areaCode,
      }));
      res.unshift({
        isAll: true,
        areaName: '全部',
        areaCode: '',
      });
      dataInfo.tabs.list = res;
      if (!dataInfo.tabs.active) {
        clickTabs(res[0]);
      }
    });
  };
  // 获取tabs数据
  const clickTabs = (row: any) => {
    if (row) {
      dataInfo.tabs.active = row.areaCode;
      dataInfo.table.title = `${page.title}【${row.areaName}】`;
      dataInfo.table.checkbox.list = [];
      getTbody();
    }
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.WarehouseAreaShelf.GetMatchPageWarehouseAreasShelf({
      ..._table.search,
      warehouseAreaCode: dataInfo.tabs.active, //分组编码
      warehouseCode: dataInfo.warehouseCode, //分组编码
    })
      .then((res: any) => {
        _table.tbody = res.list;
        _table.search.totalCount = res.totalCount;
        dataInfo.loading = false;
      })
      .catch(() => {
        dataInfo.loading = false;
      });
  };
  // 导出数据
  const exportBtn = (tbody: any[]) => {
    proxy.$exportData(
      {
        thead: dataInfo.table.thead,
        tbody: tbody,
        fileName: dataInfo.table.title,
      },
      dataInfo,
    );
    setTimeout(() => {
      dataInfo.loading = false;
    }, 1000);
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };
  // 获取仓库
  const getWarehouse = () => {
    proxy.$api.Business.GetWarehousePageDataList({
      pageIndex: 1,
      pageSize: 1,
      warehouseState: -1,
    })
      .then((res: any) => {
        const warehouseCode = res.list[0]?.warehouseCode || '';
        dataInfo.warehouseCode = warehouseCode;
        getTabs();
      })
      .catch(() => {});
  };
  // 组件挂载后执行
  onMounted(() => {});
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, getWarehouse, getTabs, options };
}
